<template>
  <div>
    <el-card>
      <el-steps :active="active" align-center>
        <el-step title="商品信息" />
        <el-step title="商品详情" />
        <el-step title="其他设置" />
      </el-steps>
      <el-divider />
      <el-form v-if="active === 0" ref="formRef" :model="form" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName" :label-width="formLabelWidth">
              <el-input v-model="form.goodsName" autocomplete="off" placeholder="请输入商品名称" style="width: 300px" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="categoryId" :label-width="formLabelWidth">
              <el-tree-select
                v-model="form.categoryId"
                :data="treeData"
                :props="treeProps"
                :render-after-expand="false"
                style="width: 300px"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品关键字" prop="goodsKeyword" :label-width="formLabelWidth">
              <el-input v-model="form.goodsKeyword" autocomplete="off" placeholder="请输入商品关键字" style="width: 300px" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品单位" prop="goodsUnit" :label-width="formLabelWidth">
              <el-input v-model="form.goodsUnit" autocomplete="off" placeholder="请输入商品单位" style="width: 300px" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品封面图" prop="goodsCoverUrl" :label-width="formLabelWidth">
          <div class="icon-category" @click="openUpload">
            <el-icon v-if="!form.goodsCoverUrl" size="30"><Camera /></el-icon>
            <el-image 
                v-else
                style="width: 50px;height: 50px;"
                :src="form.goodsCoverUrl" 
                fit="cover"/>
          </div>
          <div style="margin-left: 10px;background: #E6A23C;border-radius: 5px;color: white;"><span>上传封面图不得大于5M</span></div>
        </el-form-item>
        <el-form-item label="商品轮播图" prop="goodsCarouselUrl" :label-width="formLabelWidth">
          <div v-for="(item, index) in carouselDatas" :key="index">
            <div class="icon-category-multiple" @click="openCarouseUpload">
              <el-icon v-if="item.isShow" size="30"><Camera /></el-icon>
              <el-image 
                  v-else
                  style="width: 50px;height: 50px;"
                  :src="item.url" 
                  fit="cover"/>
            </div>
          </div>
          <div style="margin-left: 10px;background: #E6A23C;border-radius: 5px;color: white;"><span>最多上传10张轮播图</span></div>
        </el-form-item>
        <el-form-item label="主图视频" prop="goodsVideoUrl" :label-width="formLabelWidth">
          <el-input v-model="form.goodsVideoUrl" autocomplete="off" placeholder="请输入主图视频连接" style="width: 300px" clearable />
          <el-button style="margin-left: 20px;" :icon="Upload" @click="openVideo">选择视频</el-button>
        </el-form-item>
        <el-form-item label="运费模版" prop="freightTemplateId" :label-width="formLabelWidth">
          <el-select v-model="form.freightTemplateId" placeholder="请选择运费模版" style="width: 300px">
            <el-option
              v-for="item in freightTemplateData"
              :key="item.id"
              :label="item.feightTemplateName"
              :value="item.id"
            />
          </el-select>
          <el-button style="margin-left: 20px;" @click="openFeightTemplate">运费模版</el-button>
        </el-form-item>
        <el-form-item label="商品规格" prop="goodsSpecType" :label-width="formLabelWidth">
          <el-radio-group v-model="form.goodsSpecType" @change="goodsSpecTypeChange">
            <el-radio value="0" size="large">单规格</el-radio>
            <el-radio value="1" size="large">多规格</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.goodsSpecType === '1'" label="选择规格" prop="goodsName" :label-width="formLabelWidth">
          <el-select v-model="form.specId" placeholder="请选择规格" style="width: 300px">
            <el-option
              v-for="item in specData"
              :key="item.id"
              :label="item.specName"
              :value="item.id"
            />
          </el-select>
          <el-button style="margin-left: 10px;" type="primary" @click="specSure">确定</el-button>
          <el-button @click="addSpec">添加规格</el-button>
        </el-form-item>
        <el-form-item v-if="form.goodsSpecType === '1'">
          <template #default="scope">
            <spec-template ref="specTemplateRef" :goodsSpecData="goodsSpecData" @specSetData="onSpecSetData"></spec-template>
          </template>
        </el-form-item>
        <el-form-item v-if="form.goodsSpecType === '1' && matchSpecIsShow" label="批量设置">
          <template #default="scope">
            <el-table :data="batchSpecData" style="width: 100%" border stripe>
              <el-table-column property="imgUrl" label="图片" align="center">
                <template #default="scope">
                  <div class="icon-category" @click="openMatchSpecSettingUpload">
                    <el-icon v-if="!scope.row.imgUrl" size="30"><Camera /></el-icon>
                    <el-image 
                        v-else
                        style="width: 50px;height: 50px;"
                        :src="scope.row.imgUrl" 
                        fit="cover"/>
                  </div>
                </template>
              </el-table-column>
              <el-table-column property="salePrice" label="售价" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.salePrice" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="costPrice" label="成本价" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.costPrice" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="originalPrice" label="原价" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.originalPrice" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="stock" label="库存" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.stock" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="itemCode" label="商品编号" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.itemCode" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="weight" label="重量（KG）" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.weight" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="volume" label="体积（m³）" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.volume" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button size="small" @click="batchAdd(scope.row)">
                    批量添加
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-form-item>
        <el-form-item v-if="form.goodsSpecType === '1' && matchSpecIsShow" label="商品属性">
          <template #default="scope">
            <el-table :data="muchSpecData" style="width: 100%" border stripe>
              <el-table-column v-for="(item, index) in muchSpecKeys" :key="index" :label="item.specKey" align="center">
                <template #default="scope">
                  {{ scope.row[`key${index}`] }}
                </template>
              </el-table-column>
              <el-table-column property="imgUrl" label="图片" align="center">
                <template #default="scope">
                  <div class="icon-category" @click="openGoodsSpecUpload(scope)">
                    <el-icon v-if="!scope.row.imgUrl" size="30"><Camera /></el-icon>
                    <el-image 
                        v-else
                        style="width: 50px;height: 50px;"
                        :src="scope.row.imgUrl" 
                        fit="cover"/>
                  </div>
                </template>
              </el-table-column>
              <el-table-column property="salePrice" label="售价" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.salePrice" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="costPrice" label="成本价" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.costPrice" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="originalPrice" label="原价" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.originalPrice" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="stock" label="库存" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.stock" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="itemCode" label="商品编号" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.itemCode" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="weight" label="重量（KG）" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.weight" size="small" />
                </template>
              </el-table-column>
              <el-table-column property="volume" label="体积（m³）" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.volume" size="small" />
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-form-item>
        <el-form-item v-if="form.goodsSpecType === '0'" :label-width="formLabelWidth">
          <el-table :data="singleSpecData" style="width: 100%" border stripe>
            <el-table-column property="imgUrl" label="图片" align="center">
              <template #default="scope">
                <div class="icon-category" @click="openOnlySpecUpload">
                  <el-icon v-if="!scope.row.imgUrl" size="30"><Camera /></el-icon>
                  <el-image 
                      v-else
                      style="width: 50px;height: 50px;"
                      :src="scope.row.imgUrl" 
                      fit="cover"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column property="salePrice" label="售价" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.salePrice" size="small" />
              </template>
            </el-table-column>
            <el-table-column property="costPrice" label="成本价" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.costPrice" size="small" />
              </template>
            </el-table-column>
            <el-table-column property="originalPrice" label="原价" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.originalPrice" size="small" />
              </template>
            </el-table-column>
            <el-table-column property="stock" label="库存" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.stock" size="small" />
              </template>
            </el-table-column>
            <el-table-column property="itemCode" label="商品编号" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.itemCode" size="small" />
              </template>
            </el-table-column>
            <el-table-column property="weight" label="重量（KG）" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.weight" size="small" />
              </template>
            </el-table-column>
            <el-table-column property="volume" label="体积（m³）" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.volume" size="small" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <feight-template ref="feightTemplateRef" @refreshDataList="onQueryFeightTemplate"></feight-template>
      <common-upload ref="commonUploadRef" @selectImgUrl="setImgUrl"></common-upload>
      <spec-add-or-update ref="specAddOrUpdateRef" @refreshDataList="onQuerySpec"></spec-add-or-update>
      <div v-if="active === 1" class="detail-img">
        <div class="icon-detail-multiple" @click="openDetailUpload">
          <el-icon size="100"><Camera /></el-icon>
        </div>
        <div v-for="(item, index) in detailImgs" :key="index">
          <el-image 
            v-if="item.url"
            :src="item.url" 
            fit="cover"/>
        </div>
        <common-upload ref="detailUploadRef" @selectImgUrl="detailImgUrl"></common-upload>
      </div>
      <div v-if="active === 2">
        <el-form ref="otherFormRef" :model="otherForm">
          <el-row>
            <el-col :span="8">
              <el-form-item label="排序" prop="sort" :label-width="formLabelWidth">
                <el-input-number v-model="otherForm.sort" :min="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="积分" prop="points" :label-width="formLabelWidth">
                <el-input-number v-model="otherForm.points" :min="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="虚拟销量" prop="virtualSalesVolume" :label-width="formLabelWidth">
                <el-input-number v-model="otherForm.virtualSalesVolume" :min="0"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="优惠券" prop="coupone" :label-width="formLabelWidth">
            <lov-template :placeholder="lovPlaceholder" @setLovValue="setLovValue" v-model="setValue"></lov-template>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-left: 100px;">
        <el-button v-if="active > 0" type="primary" @click="upStep">上一步</el-button>
        <el-button v-if="active < 2" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="active === 2" type="primary" @click="handlerSave">确定</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
  import { reactive, ref } from 'vue'
  import { ElMessageBox } from 'element-plus'
  import { showMessage } from '~/utils/my-notification'
  import { Upload } from '@element-plus/icons-vue'
  import FeightTemplate from '../delivery/feight-template.vue'
  import CommonUpload from '~/components/upload/upload.vue'
  import SpecAddOrUpdate from './spec-add-or-update.vue'
  import SpecTemplate from './spec-template.vue'
  import { getFeightTemplate, getCategory, getSpec, getSpecInfo, saveOrUpdate, getGoodsInfo } from '~/api/product/goods'
  import LovTemplate from '../../components/lov/lov-template.vue'
  import { useRouter, useRoute } from 'vue-router'

  // 使用 useRouter 创建一个 router 实例
  const router = useRouter()
  const route = useRoute()

  const formLabelWidth = '100px'
  const formRef = ref(null)
  const treeData = ref([]) // 商品分类数据
  const freightTemplateData = ref([]) // 运费模版
  const active = ref(0)
  const feightTemplateRef = ref(null)
  const treeProps = { label: 'categoryName', children: 'children', value: 'id' }
  const commonUploadRef = ref(null)
  const uploadIndex = ref(0) // 标识当前打开的是哪个上传组件，0:封面图；1:轮播图；2:视频；
  const carouselDatas = ref([{isShow: true, url: ''}]) // 轮播图的数据
  const singleSpecData = ref([
    {
      imgUrl: '',
      salePrice: 0,
      costPrice: 0,
      originalPrice: 0,
      stock: 0,
      itemCode: '',
      weight: 0,
      volume: 0
    }
  ]) // 单规格表格数据
  const multipleSpecData = ref([]) // 多规格表格数据
  const specData = ref([]) // 商品规格下拉框数据
  const specAddOrUpdateRef = ref([]) // 添加商品规格弹窗
  const specTemplateRef = ref(null)
  const goodsSpecData = ref({}) // 商品规格父组件向子组件传递的数据
  const matchSpecIsShow = ref(false) // 多规格时，批量设置和商品属性是否显示
  const muchSpecData = ref([]) // 多规格时，商品属性
  const muchSpecKeys = ref([]) // 多规格表格动态添加的列名
  const batchSpecData = ref([]) // 批量添加表格的数据
  const detailImgs = ref([{isShow: true, url: ''}]) // 商品详情数据
  const detailUploadRef = ref(null)
  const otherFormRef = ref(null)
  const lovPlaceholder = ref('请选择优惠券')
  const goodsSpecImgIndex = ref(0) // 商品属性中当前点击的是哪一个图片
  const setValue = ref('')

  const otherForm = reactive({
    sort: 0,
    points: 0,
    virtualSalesVolume: 0,
    coupone: 0
  })

  const form = reactive({
    id: 0,
    goodsName: '',
    categoryId: '',
    goodsKeyword: '',
    goodsUnit: '',
    goodsCoverId: 0,
    goodsCoverUrl: '',
    goodsCarouselUrl: '',
    goodsCarouselIds: '',
    goodsVideoUrl: '',
    freightTemplateId: '',
    goodsSpecType: '0',
    specId: '',
    goodsDetailIds: ''
  })
  const rules = {
    goodsName: [
      { required: true, message: '商品名称不能为空!', trigger: 'blur' }
    ],
    categoryId: [
      { required: true, message: '商品分类不能为空!', trigger: 'blur' }
    ],
    goodsKeyword: [
      { required: true, message: '商品关键字不能为空!', trigger: 'blur' }
    ],
    goodsUnit: [
      { required: true, message: '商品单位不能为空!', trigger: 'blur' }
    ]
  }

  init();
  // 初始化
  function init() {
    const id = route.query.id
    // 查询商品分类数据
    onQueryCategory()
    // 查询运费模版
    onQueryFeightTemplate()
    // 查询所有商品规格
    onQuerySpec()
    if(id) {
      // 查询商品详情
      getGoodsInfo(id).then(res => {
        if(res && res.data.code === 200) {
          const data = res.data.data
          form.goodsName = data.goodsName
          form.id = data.id
          form.categoryId = data.categoryId
          form.goodsKeyword = data.goodsKeyword
          form.goodsUnit = data.goodsUnit
          // 商品封面图
          form.goodsCoverId = data.goodsCoverId
          form.goodsCoverUrl = data.goodsCoverUrl
          // 商品轮播图
          form.goodsCarouselIds = data.goodsCarouselIds
          carouselDatas.value = data.goodsCarouselUrls
          // 主图视频
          form.goodsVideoUrl = data.goodsVideoUrl
          // 运费模版
          form.freightTemplateId = data.freightTemplateId
          // 商品规格
          form.goodsSpecType = data.goodsSpecType + ''
          if(data.goodsSpecType === 0) {
            // 单规格展示
            singleSpecData.value = []
            singleSpecData.value.push(data.singleSpecData)
          } else {
            // 多规格展示
            form.specId = data.specId
            matchSpecIsShow.value = true
            goodsSpecData.value = data.spec
            // 多规格表格列动态添加的数据
            muchSpecKeys.value = data.muchSpecKeys
            // 多规格表格数据
            // setEditMatchSpecData(data.muchSpecData)
            // muchSpecData.value = data.muchSpecData
            let datas = []
            data.muchSpecData.forEach(item => {
              const valueMap = item.valueMap
              const data = mergeObjects(item, valueMap)
              datas.push(data)
            })
            muchSpecData.value = datas
          }
          // 商品详情图片
          form.goodsDetailIds = data.goodsDetailIds
          detailImgs.value = data.goodsDetailUrls
          // 其他设置
          otherForm.sort = data.sort
          otherForm.points = data.points
          otherForm.virtualSalesVolume = data.virtualSalesVolume
          otherForm.coupone = data.coupone
          setValue.value = data.couponeName
        }
      })
    }
  }
  // 合并两个对象
  function mergeObjects(obj1, obj2) {
    return Object.assign({}, obj1, obj2);
  }
  // 查询商品分类数据
  function onQueryCategory() {
    getCategory().then(res => {
      if(res && res.data.code === 200) {
        treeData.value = res.data.data
      }
    })
  }
  // 打开上传组件
  function openUpload() {
    uploadIndex.value = 0
    if(commonUploadRef.value) {
      commonUploadRef.value.init(false)
    }
  }
  // 查询运费模版
  function onQueryFeightTemplate() {
    getFeightTemplate().then(res => {
      if(res && res.data.code === 200) {
        freightTemplateData.value = res.data.data
      }
    })
  }
  // 查询所有商品规格
  function onQuerySpec() {
    getSpec().then(res => {
      if(res && res.data.code === 200) {
        specData.value = res.data.data
      }
    })
  }
  // 选中的图片放入表单中
  function setImgUrl(selectImg) {
    if(uploadIndex.value === 0) {
      form.goodsCoverUrl = selectImg.url
      form.goodsCoverId = selectImg.id
    } else if(uploadIndex.value === 1) {
      carouselDatas.value = [{isShow: true, url: ''}]
      if(selectImg.length < 10) {
        selectImg.forEach(element => {
          element.isShow = false
          carouselDatas.value.push(element)
          form.goodsCarouselIds = form.goodsCarouselIds + element.id + ','
        });
      } else if(selectImg.length >= 10) {
        // 只取前十条数据
        carouselDatas.value = []
        selectImg.forEach((element, index) => {
          if(index < 10) {
            element.isShow = false
            carouselDatas.value.push(element)
            form.goodsCarouselIds = form.goodsCarouselIds + element.id + ','
          }
        });
      }
    } else if(uploadIndex.value === 2) {
      // 视频
      form.goodsVideoUrl = selectImg.url
    } else if(uploadIndex.value === 3) {
      // 单规格图片上传
      const singleData = singleSpecData.value[0]
      singleSpecData.value = [
        { 
          imgUrl: selectImg.url,
          salePrice: singleData.salePrice,
          costPrice: singleData.costPrice,
          originalPrice: singleData.originalPrice,
          stock: singleData.stock,
          itemCode: singleData.itemCode,
          weight: singleData.weight,
          volume: singleData.volume
        }
      ]
    } else if(uploadIndex.value === 4) {
      if(batchSpecData.value.length > 0) {
        const batchData = batchSpecData.value[0]
        batchSpecData.value = [{
          imgUrl: selectImg.url,
          salePrice: batchData.salePrice,
          costPrice: batchData.costPrice,
          originalPrice: batchData.originalPrice,
          stock: batchData.stock,
          itemCode: batchData.itemCode,
          weight: batchData.weight,
          volume: batchData.volume
        }]
      } else {
        // 批量设置图片上传
        batchSpecData.value = [{
          imgUrl: selectImg.url,
          salePrice: 0,
          costPrice: 0,
          originalPrice: 0,
          stock: 0,
          itemCode: '',
          weight: 0,
          volume: 0
        }]
      }
    } else {
      // 商品属性图片上传
      const muchData = muchSpecData.value[goodsSpecImgIndex.value]
      muchData.imgUrl = selectImg.url
      muchSpecData.value[goodsSpecImgIndex.value] = muchData
    }
  }
  // 打开商品轮播图上传组件
  function openCarouseUpload() {
    uploadIndex.value = 1
    if(commonUploadRef.value) {
      commonUploadRef.value.init(true)
    }
  }
  // 选择视频
  function openVideo() {
    uploadIndex.value = 2
    if(commonUploadRef.value) {
      commonUploadRef.value.init(false, 'video')
    }
  }
  // 单规格表中的图片上传
  function openOnlySpecUpload() {
    uploadIndex.value = 3
    if(commonUploadRef.value) {
      commonUploadRef.value.init(false)
    }
  }
  // 批量设置中的图片上传
  function openMatchSpecSettingUpload() {
    uploadIndex.value = 4
    if(commonUploadRef.value) {
      commonUploadRef.value.init(false)
    }
  }
  // 商品属性中的图片上传
  function openGoodsSpecUpload(row) {
    // 当前点击的是哪一个图片
    const index = row.$index
    goodsSpecImgIndex.value = index
    uploadIndex.value = 5
    if(commonUploadRef.value) {
      commonUploadRef.value.init(false)
    }
  }
  // 商品规格改变事件
  function goodsSpecTypeChange(val) {
    form.goodsSpecType = val
    if(val === '0') {
      matchSpecIsShow.value = false
    }
  }
  // 下一步
  function nextStep() {
    if(active.value === 0) { // 说明此时是在商品信息的step中
      // 这里要把需要判断的都判断了，如果都通过了，在执行下一步，否则提示
      formRef.value.validate((valid) => {
        if(!valid) {
          return
        }
        // 封面图必填
        if(isEmpty(form.goodsCoverUrl)) {
          showMessage('请选择封面图', 'error')
          return
        }
        // 轮播图必填
        if(isEmpty(form.goodsCarouselIds)) {
          showMessage('至少选择一张轮播图', 'error')
          return
        }
        // 规格必选
        if(form.goodsSpecType === '1' && isEmpty(form.specId)) {
          showMessage('请选择规格', 'error')
          return
        }
        if(form.goodsSpecType === '0') {
          form.singleSpecData = singleSpecData.value[0]
        } else {
          for(let j = 0;j < muchSpecData.value.length;j ++) {
            const muchData = muchSpecData.value[j]
            let specValues = []
            for(let i=0;i<muchSpecKeys.value.length;i++) {
              const key = muchSpecKeys.value[i].specKey
              const value = muchData[`key${i}`]
              const data = {}
              data[key] = value
              specValues.push(data)
            }
            muchData.specValues = JSON.stringify(specValues)
          }
          form.muchSpecData = muchSpecData.value
        }
        active.value ++
      })
    } else if(active.value === 1) {
      if(detailImgs.value.length < 2 && isEmpty(detailImgs.value[0].url)) {
        showMessage('请上传详情页面的图片', 'error')
        return
      }
      active.value ++
    }
  }
  // 最后的保存或者修改
  function handlerSave() {
    ElMessageBox.confirm(`确定进行保存操作?`, '提示',{
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }).then(() => {
      form.sort = otherForm.sort
      form.points = otherForm.points
      form.virtualSalesVolume = otherForm.virtualSalesVolume
      form.coupone = otherForm.coupone
      saveOrUpdate(form).then(res => {
        if(res && res.data.code === 200) {
          showMessage('保存成功!')
          // 跳转回查询页面
          router.push({ path: './goods'})
        }
      })
    }).catch(err => {
      console.log(err)
    })
  }
  // 判断是否为空
  function isEmpty(value) {
    return value === null || value === undefined || value === "";
  }
  // 上一步
  function upStep() {
    if(active.value -- < 0) {
      return
    }
  }
  // 打开运费模版
  function openFeightTemplate() {
    if(feightTemplateRef.value) {
      feightTemplateRef.value.init()
    }
  }
  // 商品规格确定
  function specSure() {
    getSpecInfo(form.specId).then(res => {
      if(res && res.data.code === 200) {
        goodsSpecData.value = res.data.data
        // 多规格表格列动态添加的数据
        muchSpecKeys.value = goodsSpecData.value.specValue
        // 多规格表格数据
        setMatchSpecData(goodsSpecData.value.specValue)
        
      }
    })
    batchSpecData.value = [{
      imgUrl: '',
      salePrice: 0,
      costPrice: 0,
      originalPrice: 0,
      stock: 0,
      itemCode: '',
      weight: 0,
      volume: 0
    }]
    matchSpecIsShow.value = true
  }
  // 使用笛卡尔积重新组装多规格表格的数据
  function setMatchSpecData(data) {
    // 提取所有specValues形成二维数组
    const specs = data.map(item => item.specValues);

    // 计算笛卡尔积
    const result = specs.reduce((acc, current) =>
      acc.flatMap(x => current.map(y => [...x, y])),
      [[]]
    );
    // console.log(result)

    let datas = []
    // 重新组装
    result.forEach(item => {
      let a = {
        imgUrl: '',
        salePrice: 0,
        costPrice: 0,
        originalPrice: 0,
        stock: 0,
        itemCode: '',
        weight: 0,
        volume: 0
      }
      item.forEach((val, i) => {
        a[`key${i}`] = val
      })
      datas.push(a)
    })
    // console.log(datas)
    muchSpecData.value = datas
  }
  // 添加规格
  function addSpec() {
    if(specAddOrUpdateRef.value) {
      specAddOrUpdateRef.value.init()
    }
  }
  // 商品规格新增规格
  function onSpecSetData(specData) {
    
    goodsSpecData.value = specData
    // 多规格表格数据
    setMatchSpecData(goodsSpecData.value.specValue)
  }
  // 批量添加
  function batchAdd() {
    const specData = batchSpecData.value[0]
    muchSpecData.value.forEach(item => {
      item.imgUrl = specData.imgUrl
      item.salePrice = specData.salePrice
      item.costPrice = specData.costPrice
      item.originalPrice = specData.originalPrice
      item.stock = specData.stock
      item.itemCode = specData.itemCode
      item.weight = specData.weight
      item.volume = specData.volume
    })
  }
  // 打开商品详情上传组件
  function openDetailUpload() {
    if(detailUploadRef.value) {
      detailUploadRef.value.init(true)
    }
  }
  // 通过商品详情上传组件为上商品详情赋值
  function detailImgUrl(selectImg) {
    selectImg.forEach(element => {
      element.isShow = false
      detailImgs.value.push(element)
      form.goodsDetailIds = form.goodsDetailIds + element.id + ','
    });
  }
  // 为lov设置值
  function setLovValue(data) {
    otherForm.coupone = data.id
  }
</script>
<style>
  .icon-category {
    width: 50px;
    height: 50px;
    border: 1px solid #898484;
    border-style: dashed;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }

  .icon-category-multiple {
    width: 50px;
    height: 50px;
    border: 1px solid #898484;
    border-style: dashed;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    margin-right: 10px;
  }

  .detail-img {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .icon-detail-multiple {
    width: 150px;
    height: 150px;
    border: 1px solid #898484;
    border-style: dashed;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    margin-right: 10px;
    margin-bottom: 10px;
  }

</style>